package com.woniu.supermarket.web;

import com.github.pagehelper.PageInfo;
import com.woniu.supermarket.entity.LoginLog;
import com.woniu.supermarket.result.ResultResponse;
import com.woniu.supermarket.service.ILoginLogService;
import com.woniu.supermarket.util.IpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("loginLog")
@Api(value = "登录日志操作")
public class LoginLogController {

    @Autowired
    ILoginLogService iLoginLogService;

    @GetMapping("/showLog")
    @ApiOperation(value = "分页查询登录日志操作")
    public ResultResponse<PageInfo<LoginLog>> showLog(@ApiParam(name = "now",value = "当前页")@RequestParam(name = "now",defaultValue = "1") Integer now,
                                                      @ApiParam(name = "size",value = "页大小")@RequestParam(name = "size",defaultValue = "3")Integer size,
                                                      @ApiParam(name = "name",value = "用户名")String name){
        ResultResponse<PageInfo<LoginLog>> result = null;
        try {
            PageInfo<LoginLog> pageInfo = iLoginLogService.findByCons(now, size, name);
            result = new ResultResponse<>(200,"查询登录日志成功",pageInfo);
        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"查询登录日志失败");
        }
        return result;
    }


    @PostMapping("/addLog")
    public ResultResponse<Void> addLog(@RequestBody LoginLog loginLog,HttpServletRequest request){
        ResultResponse<Void> result = null;

        String ip = IpUtil.getIpAddr(request);
        try {
            loginLog.setIp(ip);
            int i = iLoginLogService.addLog(loginLog);
            result = new ResultResponse<>(200,"添加登录日志成功");
        }catch (RuntimeException e){
            e.printStackTrace();
            result = new ResultResponse<>(201,"添加登录日志失败");
        }
        return result;
    }

    @GetMapping("/urlName")
    @ApiOperation(value = "获取ip操作")
    public String MethodName(HttpServletRequest request){
        String ip = IpUtil.getIpAddr(request);

        return ip;
    }
}
